package cn.ug.operation.web.controller;

import cn.ug.activity.bean.MemberInvestmentRewardsBean;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Order;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.login.LoginHelper;
import cn.ug.feign.MemberUserService;
import cn.ug.member.bean.response.MemberUserBean;
import cn.ug.operation.bean.*;
import cn.ug.operation.mapper.entity.LotteryJoinMember;
import cn.ug.operation.mapper.entity.LotteryPrize;
import cn.ug.operation.service.LotteryJoinMemberService;
import cn.ug.operation.service.LotteryMemberService;
import cn.ug.operation.service.LotteryService;
import cn.ug.util.DateUtils;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import cn.ug.web.controller.ExportExcelController;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/lottery")
public class LotteryController extends BaseController {
    @Autowired
    private LotteryService lotteryService;
    @Autowired
    private LotteryJoinMemberService lotteryJoinMemberService;
    @Autowired
    private LotteryMemberService lotteryMemberService;

    @Autowired
    private MemberUserService memberUserService;

    @PutMapping("/remove")
    public SerializeObject delete(@RequestHeader String accessToken, int[] id) {
        if(null == id || id.length <= 0) {
            return new SerializeObjectError("00000002");
        }
        if (lotteryService.deleteByIds(id)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PutMapping("/end")
    public SerializeObject end(@RequestHeader String accessToken, int[] id) {
        if(null == id || id.length <= 0) {
            return new SerializeObjectError("00000002");
        }
        if (lotteryService.toFinish(id)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PutMapping("/publish")
    public SerializeObject publish(@RequestHeader String accessToken, int[] id) {
        if(null == id || id.length <= 0) {
            return new SerializeObjectError("00000002");
        }
        if (lotteryService.publish(id)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @GetMapping(value = "/{id}")
    public SerializeObject get(@PathVariable int id) {
        if(id < 1) {
            return new SerializeObjectError("00000002");
        }
        LotteryBean entity = lotteryService.getLottery(id);
        if(null == entity) {
            return new SerializeObjectError("00000003");
        }
        JSONObject result = new JSONObject();
        result.put("lottery", entity);
        result.put("prizes", lotteryService.selectByLotteryId(id));
        return new SerializeObject<>(ResultType.NORMAL, result);
    }

    @GetMapping(value = "/analysis/{id}")
    public SerializeObject getAnalysis(@RequestHeader String accessToken, @PathVariable int id) {
        if(id < 1) {
            return new SerializeObjectError("00000002");
        }
        LotteryAnalysisBean entity = lotteryService.getLotteryAnalysis(id);
        if(null == entity) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @GetMapping(value = "/analysis/list")
    public SerializeObject<DataTable<LotteryAnalysisBean>> listAnalysis(@RequestHeader String accessToken, Page page, Integer status, String startDate, String endDate) {
        status = status == null ? -1 : status;
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        int total = lotteryService.countForAnalysis(status, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<LotteryAnalysisBean> list = lotteryService.queryForAnalysis(status, startDate, endDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryAnalysisBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryAnalysisBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<LotteryAnalysisBean>()));
    }

    @GetMapping(value = "/analysis/detail/list")
    public SerializeObject<DataTable<LotteryAnalysisDetailBean>> listAnalysisDetail(@RequestHeader String accessToken, Page page, int lotteryId, String startDate, String endDate) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        int total = lotteryJoinMemberService.countForAnalysisDetail(lotteryId, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<LotteryAnalysisDetailBean> list = lotteryJoinMemberService.queryForAnalysisDetail(lotteryId, startDate, endDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryAnalysisDetailBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryAnalysisDetailBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<LotteryAnalysisDetailBean>()));
    }

    @GetMapping(value = "/analysis/detail/export")
    public void exportAnalysisDetail(HttpServletResponse response, int lotteryId, String startDate, String endDate) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        List<LotteryAnalysisDetailBean> list = lotteryJoinMemberService.queryForAnalysisDetail(lotteryId, startDate, endDate, 0, 0);
        if(list != null && !list.isEmpty()){
            String[] columnNames = { "序号", "日期","参与人数", "抽奖次数", "中奖人数", "领取人数","新增人数"};
            String [] columns = {"index",  "drawDate", "joinNum", "drawNum", "prizeNum", "receiveNum","newAddNum"};
            String fileName = "抽奖活动数据分析详表";
            int index = 1;
            for (LotteryAnalysisDetailBean bean : list) {
                bean.setIndex(index);
                index++;
            }
            ExportExcelController<LotteryAnalysisDetailBean> export = new ExportExcelController<LotteryAnalysisDetailBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/everyday/prize/list")
    public SerializeObject<DataTable<EverydayPrizeBean>> listEverydayPrizes(@RequestHeader String accessToken, Page page, int lotteryId, String drawDate) {
        drawDate = UF.toString(drawDate);
        int total = lotteryJoinMemberService.countForEverydayPrizes(lotteryId, drawDate);
        page.setTotal(total);
        if (total > 0) {
            List<EverydayPrizeBean> list = lotteryJoinMemberService.queryForEverydayPrizes(lotteryId, drawDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<EverydayPrizeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<EverydayPrizeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<EverydayPrizeBean>()));
    }

    @GetMapping(value = "/everyday/prize/export")
    public void exportEverydayPrizes(HttpServletResponse response, int lotteryId, String drawDate) {
        drawDate = UF.toString(drawDate);
        List<EverydayPrizeBean> list = lotteryJoinMemberService.queryForEverydayPrizes(lotteryId, drawDate, 0, 0);
        if(list != null && !list.isEmpty()){
            String[] columnNames = { "序号", "奖品名称","奖品消耗量/奖品数量", "中奖人数", "领取人数"};
            String [] columns = {"index",  "prizeName", "remark", "getPrizeNum", "receiveNum"};
            String fileName = "单日奖品明细表";
            int index = 1;
            for (EverydayPrizeBean bean : list) {
                bean.setIndex(index);
                if (bean.getTotalNum() > 0) {
                    bean.setRemark(bean.getConsumeNum()+"/"+bean.getTotalNum());
                } else {
                    bean.setRemark(bean.getConsumeNum()+"/不限数量");
                }
                index++;
            }
            ExportExcelController<EverydayPrizeBean> export = new ExportExcelController<EverydayPrizeBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/list")
    public SerializeObject<DataTable<LotteryActivityBean>> list(@RequestHeader String accessToken, Page page, Integer status, String startDate, String endDate) {
        status = status == null ? -1 : status;
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        int total = lotteryService.count(status, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<LotteryActivityBean> list = lotteryService.query(status, startDate, endDate, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryActivityBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryActivityBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<LotteryActivityBean>()));
    }

    @GetMapping(value = "/statistics/list")
    public SerializeObject<DataTable<LotteryStatisticsBean>> listStatistics(@RequestHeader String accessToken, Page page, String lotteryName, String prizeName) {
        lotteryName = UF.toString(lotteryName);
        prizeName = UF.toString(prizeName);
        int total = lotteryService.countForStatistics(lotteryName, prizeName);
        page.setTotal(total);
        if (total > 0) {
            List<LotteryStatisticsBean> list = lotteryService.queryForStatistics(lotteryName, prizeName, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryStatisticsBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryStatisticsBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<LotteryStatisticsBean>()));
    }

    @GetMapping(value = "/member/prize/list")
    public SerializeObject<DataTable<MemberPrizeBean>> queryPrizeForList(@RequestHeader String accessToken, Page page, Integer lotteryId, String memberId, Integer status, String lotteryName) {
        memberId = UF.toString(memberId);
        lotteryName = UF.toString(lotteryName);
        status = status == null ? -1 : status;
        lotteryId = lotteryId == null ? 0 : lotteryId;
        int total = lotteryMemberService.queryForCount(lotteryId, memberId, status, lotteryName);
        page.setTotal(total);
        if (total > 0) {
            List<MemberPrizeBean> list = lotteryMemberService.queryForList(lotteryId, memberId, status, lotteryName, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberPrizeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberPrizeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<MemberPrizeBean>()));
    }



    @GetMapping(value = "/member/list")
    public SerializeObject<DataTable<LotteryMemberBean>> queryMemberForList(@RequestHeader String accessToken, Page page, Integer lotteryStatus, Integer prizeStatus, String lotteryName) {
        lotteryName = UF.toString(lotteryName);
        lotteryStatus = lotteryStatus == null ? -1 : lotteryStatus;
        prizeStatus = prizeStatus == null ? -1 : prizeStatus;
        int total = lotteryMemberService.queryForMemberCount(lotteryStatus, prizeStatus, lotteryName);
        page.setTotal(total);
        if (total > 0) {
            List<LotteryMemberBean> list = lotteryMemberService.queryForMemberList(lotteryStatus, prizeStatus, lotteryName, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryMemberBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryMemberBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<LotteryMemberBean>()));
    }

    @GetMapping(value = "/member/export")
    public void exportMemberForList(HttpServletResponse response, Integer lotteryStatus, Integer prizeStatus, String lotteryName) {
        lotteryName = UF.toString(lotteryName);
        lotteryStatus = lotteryStatus == null ? -1 : lotteryStatus;
        prizeStatus = prizeStatus == null ? -1 : prizeStatus;
        List<LotteryMemberBean> list = lotteryMemberService.queryForMemberList(lotteryStatus, prizeStatus, lotteryName, 0, 0);
        if(list != null && !list.isEmpty()){
            String[] columnNames = { "序号", "活动名称","活动状态", "手机号", "姓名", "参与活动时间", "抽中奖品名称", "中奖时间", "奖品领取状态", "领取时间"};
            String [] columns = {"index",  "lotteryName", "lotteryStatus", "cellphone", "memeberName", "joinTime", "prizeName", "getPrizeTime", "prizeStatus", "receivePrizeTime"};
            String fileName = "抽奖活动中奖用户表";
            int index = 1;
            List<LotteryMemberMarkBean> data = new ArrayList<LotteryMemberMarkBean>();
            for (LotteryMemberBean bean : list) {
                LotteryMemberMarkBean markBean = new LotteryMemberMarkBean();
                markBean.setIndex(index);
                markBean.setId(bean.getId());
                markBean.setLotteryName(bean.getLotteryName());
                if (bean.getLotteryStatus() == 2) {
                    markBean.setLotteryStatus("进行中");
                } else {
                    markBean.setLotteryStatus("已结束");
                }
                markBean.setCellphone(bean.getCellphone());
                if (StringUtils.isNotBlank(bean.getMemeberName())) {
                    markBean.setMemeberName(bean.getMemeberName());
                } else {
                    markBean.setMemeberName("N/A");
                }
                markBean.setJoinTime(bean.getJoinTime());
                markBean.setPrizeName(bean.getPrizeName());
                markBean.setGetPrizeTime(bean.getGetPrizeTime());
                if (bean.getPrizeStatus() == 1) {
                    markBean.setPrizeStatus("已领取");
                    markBean.setReceivePrizeTime(bean.getReceivePrizeTime());
                } else {
                    markBean.setPrizeStatus("未领取");
                    markBean.setReceivePrizeTime("N/A");
                }
                data.add(markBean);
                index++;
            }
            ExportExcelController<LotteryMemberMarkBean> export = new ExportExcelController<LotteryMemberMarkBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, data, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/join/member/statistics/list")
    public SerializeObject<DataTable<LotteryJoinMemberBean>> listStatistics(@RequestHeader String accessToken, Page page, Order order, Integer lotteryId, String cellphone, String memberName, String channelId) {
        cellphone = UF.toString(cellphone);
        memberName = UF.toString(memberName);
        channelId = UF.toString(channelId);
        lotteryId = lotteryId == null ? 0 : lotteryId;
        int total = lotteryJoinMemberService.countForStatistics(lotteryId, cellphone, memberName, channelId);
        page.setTotal(total);
        if (total > 0) {
            List<LotteryJoinMemberBean> list = lotteryJoinMemberService.queryForStatistics(lotteryId, cellphone, memberName, channelId, order.getOrder(), order.getSort(), PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryJoinMemberBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<LotteryJoinMemberBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<LotteryJoinMemberBean>()));
    }

    @GetMapping(value = "/join/member/statistics/export")
    public void exportStatistics(HttpServletResponse response, Order order, Integer lotteryId, String cellphone, String memberName, String channelId) {
        cellphone = UF.toString(cellphone);
        memberName = UF.toString(memberName);
        channelId = UF.toString(channelId);
        lotteryId = lotteryId == null ? 0 : lotteryId;
        List<LotteryJoinMemberBean> list = lotteryJoinMemberService.queryForStatistics(lotteryId, cellphone, memberName, channelId, order.getOrder(), order.getSort(), 0, 0);
        if(list != null && !list.isEmpty()){
            String[] columnNames = { "序号", "手机号","姓名", "渠道来源", "交易次数", "抽中奖品总数量","抽奖总次数"};
            String [] columns = {"index",  "cellphone", "memberName", "channelName", "transactionNum", "prizeNum","drawNum"};
            String fileName = "抽奖活动参与用户表";
            int index = 1;
            for (LotteryJoinMemberBean bean : list) {
                bean.setIndex(index);
                index++;
                if (StringUtils.isBlank(bean.getMemberName())) {
                    bean.setMemberName("N/A");
                }
                if (StringUtils.isBlank(bean.getChannelName())) {
                    bean.setChannelName("N/A");
                }
            }
            ExportExcelController<LotteryJoinMemberBean> export = new ExportExcelController<LotteryJoinMemberBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/prize/statistics/list")
    public SerializeObject<List<PrizeStatisticsBean>> listStatistics(@RequestHeader String accessToken, int lotteryId, String prizeName) {
        List<PrizeStatisticsBean> list = lotteryService.queryForStatistics(lotteryId, prizeName);
        return new SerializeObject<>(ResultType.NORMAL, list);
    }

    @PostMapping
    public SerializeObject save(@RequestHeader String accessToken, LotteryBean lottery, String prizes) {
        if (lottery == null || StringUtils.isBlank(lottery.getName())) {
            return new SerializeObjectError("25000040");
        }
        if (StringUtils.isBlank(lottery.getTitle())) {
            return new SerializeObjectError("25000041");
        }
        if (StringUtils.isBlank(lottery.getStartTime())) {
            return new SerializeObjectError("25000042");
        }
        if (StringUtils.isBlank(lottery.getEndTime())) {
            return new SerializeObjectError("25000043");
        }
        if (StringUtils.isBlank(lottery.getRules())) {
            return new SerializeObjectError("25000044");
        }
        if (lottery.getAccumulateNum() == null) {
            return new SerializeObjectError("25000045");
        }
        if (lottery.getDefaultNum() == null) {
            return new SerializeObjectError("25000046");
        }
        if (lottery.getEverydayNum() == null) {
            return new SerializeObjectError("25000047");
        }
        if (lottery.getEverydayMaxNum() == null) {
            return new SerializeObjectError("25000048");
        }
        if (lottery.getGrantingMethod() == null) {
            return new SerializeObjectError("25000049");
        }
        if (lottery.getShareRewards() == null) {
            return new SerializeObjectError("25000050");
        }
        if (StringUtils.isBlank(lottery.getShareTitle())) {
            return new SerializeObjectError("25000051");
        }
        if (StringUtils.isBlank(lottery.getShareImg())) {
            return new SerializeObjectError("25000052");
        }
        if (StringUtils.isBlank(lottery.getShareRemark())) {
            return new SerializeObjectError("25000053");
        }
        if (StringUtils.isBlank(prizes)) {
            return new SerializeObjectError("25000054");
        }
        try {
            List<LotteryPrize> lotteryPrizeList = JSONArray.parseArray(prizes, LotteryPrize.class);
            if (lotteryPrizeList == null || lotteryPrizeList.size() == 0) {
                return new SerializeObjectError("25000054");
            }
            for (LotteryPrize lotteryPrize : lotteryPrizeList) {
                if (lotteryPrize == null || StringUtils.isBlank(lotteryPrize.getName())) {
                    return new SerializeObjectError("25000055");
                }
                if (StringUtils.isBlank(lotteryPrize.getPrizeImg())) {
                    return new SerializeObjectError("25000056");
                }
                if (lotteryPrize.getType() == null) {
                    return new SerializeObjectError("25000057");
                }
                if (lotteryPrize.getQuantityLimit() == null) {
                    return new SerializeObjectError("25000058");
                }
                if (lotteryPrize.getProbability() == null) {
                    return new SerializeObjectError("25000059");
                }
            }
            if (lotteryService.save(lottery, lotteryPrizeList)) {
                return new SerializeObject(ResultType.NORMAL, "00000001");
            } else {
                return new SerializeObject(ResultType.ERROR, "00000005");
            }
        } catch (Exception e) {
            return new SerializeObjectError("25000060");
        }
    }

    @PostMapping("/join")
    public SerializeObject join(@RequestHeader String accessToken, int lotteryId) {
        String memberId = LoginHelper.getLoginId();
        if (StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        if (lotteryId < 1) {
            return new SerializeObjectError("00000002");
        }
        LotteryBean lottery = lotteryService.getLottery(lotteryId);
        if (lottery == null || lottery.getId() == 0 || StringUtils.isBlank(lottery.getStartTime()) || StringUtils.isBlank(lottery.getEndTime())) {
            return new SerializeObjectError("00000002");
        }
        if (lottery.getStatus() == 1) {
            return new SerializeObjectError("25000031");
        }
        if (lottery.getStatus() == 3) {
            return new SerializeObjectError("25000032");
        }
        if (lottery.getStatus() != 2) {
            return new SerializeObjectError("25000031");
        }
        LotteryJoinMember lotteryJoinMember = new LotteryJoinMember();
        lotteryJoinMember.setAddTime(LocalDateTime.now());
        lotteryJoinMember.setLotteryId(lotteryId);
        lotteryJoinMember.setMemberId(memberId);
        lotteryJoinMember.setTimes(lottery.getDefaultNum());
        return lotteryJoinMemberService.save(lotteryJoinMember);
    }

    /**
     * 根据用户id，查询用户参加的活动
     * @param memberId
     * @return
     */
    @GetMapping("/findJoinLottery")
    public SerializeObject<LotteryJoin> findJoinLotteryByMember(String memberId){
        if (StringUtils.isBlank(memberId)) {
            return new SerializeObject(ResultType.ERROR,"00000002");
        }
        return lotteryJoinMemberService.findJoinLotteryByMember(memberId);
    }

    /**
     * 获取活动
     * @param lotteryId
     * @return
     */
    @GetMapping("/findLottery")
    public SerializeObject<LotteryBean> findLottery(int lotteryId){
        if (lotteryId <= 0) {
            return new SerializeObject(ResultType.ERROR,"00000002");
        }
        LotteryBean lottery = lotteryService.getLottery(lotteryId);
        if (lottery == null) {
            return new SerializeObject(ResultType.NORMAL, "00000005");
        }
        return new SerializeObject(ResultType.NORMAL, lottery);
    }

    /**
     * 获取当日抽奖次数
     * @param memberId
     * @param lotteryId
     * @return
     */
    @GetMapping("/countLotteryNumToday")
    public SerializeObject countLotteryNumToday(String memberId, int lotteryId){
        if (StringUtils.isBlank(memberId) || lotteryId <= 0) {
            return new SerializeObject(ResultType.ERROR,"00000002");
        }
        int num = lotteryMemberService.countLotteryNumToday(memberId,lotteryId);
        return new SerializeObject(ResultType.NORMAL, num);
    }

    /**
     * 增加用户抽奖次数
     * @param memberId
     * @param lotteryId
     * @return
     */
    @PostMapping("/addLotteryTimes")
    public SerializeObject addLotteryTimes (String memberId, int lotteryId) {
        if (StringUtils.isBlank(memberId) || lotteryId < 0) {
            return new SerializeObject(ResultType.ERROR,"00000002");
        }
        return new SerializeObject(ResultType.NORMAL, lotteryJoinMemberService.addMemberLotteryTimes(lotteryId,memberId));
    }

    @GetMapping(value = "/member/record")
    public SerializeObject<DataTable<MyLotteryPrizeBean>> queryMemberPrizeForList(@RequestHeader String accessToken, Page page, int lotteryId) {
        String memberId = LoginHelper.getLoginId();
        if (StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        if (lotteryId < 1) {
            return new SerializeObjectError("00000002");
        }
        int total = lotteryMemberService.countForListByMemberId(memberId, lotteryId);
        page.setTotal(total);
        if (total > 0) {
            List<MyLotteryPrizeBean> list = lotteryMemberService.queryForListByMemberId(memberId, lotteryId, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MyLotteryPrizeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<MyLotteryPrizeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<MyLotteryPrizeBean>()));
    }

    /**
     * 分享
     * @param accessToken
     * @param lotteryId   活动id
     * @param type        类型：1.首次抽奖成功  其他情况传0
     * @return
     */
    @PostMapping(value = "/share")
    public SerializeObject share(@RequestHeader String accessToken, int lotteryId,int type) {
        if (StringUtils.isBlank(accessToken) || accessToken.equalsIgnoreCase("null"))
            return new SerializeObject(ResultType.NORMAL, "00000001");

        String memberId = LoginHelper.getLoginId();
        if (StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        if (lotteryId < 1) {
            return new SerializeObjectError("00000002");
        }
        LotteryBean lottery = lotteryService.getLottery(lotteryId);
        if (lottery == null || lottery.getId() == 0 || StringUtils.isBlank(lottery.getStartTime()) || StringUtils.isBlank(lottery.getEndTime())) {
            return new SerializeObjectError("00000002");
        }
        if (lottery.getStatus() == 1) {
            return new SerializeObjectError("25000031");
        }
        if (lottery.getStatus() == 3) {
            return new SerializeObjectError("25000032");
        }
        if (lottery.getStatus() != 2) {
            return new SerializeObjectError("25000031");
        }
        if (lottery.getShareRewards() != 1) {
            return new SerializeObjectError("25000066");
        }
        return lotteryJoinMemberService.share(memberId, lottery,type);
    }

    @PostMapping(value = "/draw")
    public SerializeObject draw(@RequestHeader String accessToken, int lotteryId) {
        String memberId = LoginHelper.getLoginId();
        if (StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        if (lotteryId < 1) {
            return new SerializeObjectError("00000002");
        }
        SerializeObject<MemberUserBean> serializeObject = memberUserService.findById(memberId);
        if (serializeObject != null && serializeObject.getCode() == ResultType.NORMAL && serializeObject.getData() != null) {
            MemberUserBean memberUserBean = serializeObject.getData();
            //大转盘活动（非七夕活动） 需要控制老用户(非大转盘抽奖活动注册)不能抽奖
            if (memberUserBean.getLotteryId()==null){
                return new SerializeObjectError("25000071");
            }
        }
        LotteryBean lottery = lotteryService.getLottery(lotteryId);
        if (lottery == null || lottery.getId() == 0 || StringUtils.isBlank(lottery.getStartTime()) || StringUtils.isBlank(lottery.getEndTime())) {
            return new SerializeObjectError("00000002");
        }
        if (lottery.getStatus() == 1) {
            return new SerializeObject(503, DateUtils.dateToStr(DateUtils.strToDate(lottery.getStartTime()),"yyyy年MM月dd日"));
        }
        if (lottery.getStatus() == 3) {
            return new SerializeObject(504,  DateUtils.dateToStr(DateUtils.strToDate(lottery.getEndTime()),"yyyy年MM月dd日"));
        }
        if (lottery.getStatus() != 2) {
            return new SerializeObjectError("25000031");
        }

        return lotteryJoinMemberService.draw(memberId, lottery);
    }

    /**
     * 双十一抽奖
     * @param accessToken
     * @param lotteryId
     * @return
     */
    @PostMapping(value = "/doubleEleven/draw")
    public SerializeObject doubleElevenDraw(@RequestHeader String accessToken, int lotteryId) {
        String memberId = LoginHelper.getLoginId();
        if (StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        if (lotteryId < 1) {
            return new SerializeObjectError("00000002");
        }
        SerializeObject<MemberUserBean> serializeObject = memberUserService.findById(memberId);
        if (serializeObject == null || serializeObject.getCode() != ResultType.NORMAL || serializeObject.getData() == null) {
            return new SerializeObjectError("00000002");
        }
        LotteryBean lottery = lotteryService.getLottery(lotteryId);
        if (lottery == null || lottery.getId() == 0 || StringUtils.isBlank(lottery.getStartTime()) || StringUtils.isBlank(lottery.getEndTime())) {
            return new SerializeObjectError("00000002");
        }
        if (lottery.getStatus() == 1) {
            return new SerializeObject(503, DateUtils.dateToStr(DateUtils.strToDate(lottery.getStartTime()),"yyyy年MM月dd日"));
        }
        if (lottery.getStatus() == 3) {
            return new SerializeObject(504,  DateUtils.dateToStr(DateUtils.strToDate(lottery.getEndTime()),"yyyy年MM月dd日"));
        }
        if (lottery.getStatus() != 2) {
            return new SerializeObjectError("25000031");
        }
        return lotteryJoinMemberService.doubleElevenDraw(memberId, lottery);
    }

    /**
     * 我的奖品
     * @param accessToken
     * @param lotteryId
     * @return
     */
    @GetMapping("/getMemberPrize")
    public SerializeObject getMemberPrize (@RequestHeader String accessToken, int lotteryId, Page page) {
        String memberId = LoginHelper.getLoginId();
        if (StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        if (lotteryId < 1) {
            return new SerializeObjectError("00000002");
        }
        LotteryBean lottery = lotteryService.getLottery(lotteryId);
        if (lottery == null || lottery.getId() == 0 || StringUtils.isBlank(lottery.getStartTime()) || StringUtils.isBlank(lottery.getEndTime())) {
            return new SerializeObjectError("00000002");
        }
        /*if (lottery.getStatus() == 1) {
            return new SerializeObjectError("25000031");
        }
        if (lottery.getStatus() == 3) {
            return new SerializeObjectError("25000032");
        }
        if (lottery.getStatus() != 2) {
            return new SerializeObjectError("25000031");
        }*/

        int total = lotteryMemberService.countForListByMemberId(memberId, lottery.getId());
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<MyLotteryPrizeBean> list = lotteryMemberService.queryForListByMemberId(memberId, lottery.getId(), offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MyLotteryPrizeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }

        return new SerializeObject<>(ResultType.NORMAL, new DataTable<MyLotteryPrizeBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<MyLotteryPrizeBean>()));
    }

    /**
     * 剩余抽奖次数
     * @param accessToken
     * @param lotteryId
     * @return
     */
    @GetMapping(value = "/member/times")
    public SerializeObject getMemberTimes(@RequestHeader String accessToken, int lotteryId) {
        String memberId = LoginHelper.getLoginId();
        if (StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        if (lotteryId < 1) {
            return new SerializeObjectError("00000002");
        }
        LotteryBean lottery = lotteryService.getLottery(lotteryId);
        if (lottery == null || lottery.getId() == 0 || StringUtils.isBlank(lottery.getStartTime()) || StringUtils.isBlank(lottery.getEndTime())) {
            return new SerializeObjectError("00000002");
        }

        if (lottery.getStatus() == 1) {
            return new SerializeObjectError("25000031");
        }
        if (lottery.getStatus() == 3) {
            return new SerializeObjectError("25000032");
        }
        if (lottery.getStatus() != 2) {
            return new SerializeObjectError("25000031");
        }

        return lotteryJoinMemberService.getMemberTimes(memberId, lottery);
    }

    /**
     * 双十一抽奖-剩余抽奖次数
     * @param accessToken
     * @param lotteryId
     * @return
     */
    @GetMapping(value = "/doubleEleven/times")
    public SerializeObject getDoubleElevenTimes(@RequestHeader String accessToken, int lotteryId) {
        String memberId = LoginHelper.getLoginId();
        if (StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        if (lotteryId < 1) {
            return new SerializeObjectError("00000002");
        }
        LotteryBean lottery = lotteryService.getLottery(lotteryId);
        if (lottery == null || lottery.getId() == 0 || StringUtils.isBlank(lottery.getStartTime()) || StringUtils.isBlank(lottery.getEndTime())) {
            return new SerializeObjectError("00000002");
        }
        if (lottery.getStatus() == 1) {
            return new SerializeObject(504, DateUtils.dateToStr(DateUtils.strToDate(lottery.getStartTime()),"yyyy年MM月dd日"));
        }
        if (lottery.getStatus() == 3) {
            return new SerializeObject(505,  DateUtils.dateToStr(DateUtils.strToDate(lottery.getEndTime()),"yyyy年MM月dd日"));
        }
        if (lottery.getStatus() != 2) {
            return new SerializeObject(504, DateUtils.dateToStr(DateUtils.strToDate(lottery.getStartTime()),"yyyy年MM月dd日"));
        }
        return lotteryJoinMemberService.getDoubleElevenMemberTimes(memberId, lottery);
    }

    @GetMapping(value = "/draw/recent/list")
    public SerializeObject<List<LotteryDrawRecord>> recentList(){
        List<LotteryDrawRecord> list = lotteryMemberService.recentList();
        if (list != null && list.size() > 0) {
            for (LotteryDrawRecord bean : list) {
                if (org.apache.commons.lang3.StringUtils.isNotBlank(bean.getMobile())) {
                    bean.setMobile(org.apache.commons.lang3.StringUtils.substring(bean.getMobile(), 0, 3) +"****"+ org.apache.commons.lang3.StringUtils.substring(bean.getMobile(), 7));
                }
            }
        }
        return new SerializeObject<>(ResultType.NORMAL, list);
    }
}
